<?php
class ForgotPasswordForm extends BaseForm {
  const FORM_NAME           = 'frm';

  const FIELD_USERNAME      = 'username';

  public function configure() {

    $widgets = array(
            self::FIELD_USERNAME => new sfWidgetFormInput(array(), array())
    );

    $labels = array(
            self::FIELD_USERNAME => 'Email Address / Username'
    );

    $this->setWidgets($widgets);
    $this->widgetSchema->setLabels($labels);

    $validators = array(
            self::FIELD_USERNAME => new sfValidatorString(array('trim' => true), array('required' => LangUtil::getText('error_required', array($labels[self::FIELD_USERNAME]))))
    );

    $this->setValidators($validators);
    $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'postValidator'))));

    $this->widgetSchema->setNameFormat(self::FORM_NAME . '[%s]');

    $this->validatorSchema->setOption('allow_extra_fields', true);
    $this->validatorSchema->setOption('filter_extra_fields', false);
  }

  public function postValidator($validator, $values) {
    if (trim($values[self::FIELD_USERNAME]) != '') {
      if (function_exists('recaptcha_check_answer') && is_callable('recaptcha_check_answer')) {
        $resp = recaptcha_check_answer(sfConfig::get('app_recaptcha_api_key_private'), ServerUtil::getUserIp(), $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);

        if (!$resp->is_valid) {
          throw new sfValidatorError($validator, LangUtil::getText('error_captcha'));
        }
      }

      $user = USERTable::getInstance()->findByUsername(trim($values[self::FIELD_USERNAME]));
      if (!$user instanceof USER) {
        $error = new sfValidatorError($validator, LangUtil::getText('error_user_not_exists'));
        throw new sfValidatorErrorSchema($validator, array(self::FIELD_USERNAME => $error));
      }
    }

    return $values;
  }
}
?>